<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>成绩分析 - 教师端</title>
    <link href="/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="/css/all.min.css">
    <script src="/js/echarts.min.js"></script>
    <style>
        :root {
            --primary: #4361ee;
            --secondary: #3f37c9;
            --teacher-accent: #4361ee;
            --success: #4caf50;
            --warning: #ff9800;
            --danger: #f44336;
            --info: #2196f3;
            --light: #f8f9fa;
            --dark: #343a40;
            --card-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
            --transition: all 0.3s ease;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f5f7fb;
            color: #333;
            min-height: 100vh;
        }

        /* 导航栏样式 */
        .navbar {
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            padding: 0.8rem 1rem;
        }

        .navbar-brand {
            font-weight: 700;
            font-size: 1.5rem;
            display: flex;
            align-items: center;
        }

        .navbar-brand i {
            margin-right: 10px;
            font-size: 1.8rem;
        }

        .nav-link {
            color: rgba(255, 255, 255, 0.85) !important;
            font-weight: 500;
            padding: 0.5rem 1rem !important;
            border-radius: 4px;
            margin: 0 3px;
            transition: var(--transition);
        }

        .nav-link:hover, .nav-link.active {
            background-color: rgba(255, 255, 255, 0.15);
            color: white !important;
        }

        /* 主内容区域 */
        .main-content {
            padding: 2rem 0;
        }

        .page-header {
            background: white;
            border-radius: 15px;
            padding: 1.5rem;
            box-shadow: var(--card-shadow);
            margin-bottom: 2rem;
            position: relative;
            overflow: hidden;
        }

        .page-header::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 5px;
            height: 100%;
            background: linear-gradient(135deg, var(--primary), var(--secondary));
        }

        .page-title {
            font-weight: 700;
            margin-bottom: 0.5rem;
            color: var(--dark);
        }

        .page-subtitle {
            color: #6c757d;
            margin-bottom: 0;
        }

        /* 统计卡片 */
        .stats-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: var(--card-shadow);
            transition: var(--transition);
            height: 100%;
            border-left: 4px solid var(--primary);
        }

        .stats-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.15);
        }

        .stats-icon {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.5rem;
            color: white;
            margin-bottom: 1rem;
        }

        .stats-number {
            font-size: 2rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
        }

        .stats-label {
            color: #6c757d;
            font-size: 0.9rem;
        }

        /* 图表卡片 */
        .chart-card {
            background: white;
            border-radius: 12px;
            box-shadow: var(--card-shadow);
            margin-bottom: 2rem;
            overflow: hidden;
        }

        .chart-header {
            background: white;
            border-bottom: 1px solid rgba(0, 0, 0, 0.05);
            padding: 1.25rem 1.5rem;
            font-weight: 700;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .chart-header i {
            margin-right: 10px;
            font-size: 1.25rem;
            color: var(--primary);
        }

        .chart-body {
            padding: 1.5rem;
        }

        .chart-container {
            height: 400px;
            width: 100%;
        }

        /* 学生排名 */
        .ranking-card {
            background: white;
            border-radius: 12px;
            box-shadow: var(--card-shadow);
            margin-bottom: 2rem;
        }

        .ranking-header {
            background: white;
            border-bottom: 1px solid rgba(0, 0, 0, 0.05);
            padding: 1.25rem 1.5rem;
            font-weight: 700;
            display: flex;
            align-items: center;
        }

        .ranking-header i {
            margin-right: 10px;
            font-size: 1.25rem;
            color: var(--primary);
        }

        .ranking-item {
            padding: 1rem 1.5rem;
            border-bottom: 1px solid rgba(0, 0, 0, 0.05);
            transition: var(--transition);
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .ranking-item:hover {
            background-color: rgba(67, 97, 238, 0.05);
        }

        .ranking-item:last-child {
            border-bottom: none;
        }

        .ranking-info {
            display: flex;
            align-items: center;
        }

        .ranking-number {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: var(--primary);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 700;
            margin-right: 1rem;
        }

        .ranking-number.top3 {
            background: linear-gradient(135deg, #ffd700, #ffed4e);
            color: #333;
        }

        .student-info h6 {
            margin-bottom: 0.25rem;
            font-weight: 600;
        }

        .student-info small {
            color: #6c757d;
        }

        .ranking-score {
            text-align: right;
        }

        .ranking-score .score {
            font-size: 1.25rem;
            font-weight: 700;
            color: var(--primary);
        }

        .ranking-score .exam-count {
            font-size: 0.875rem;
            color: #6c757d;
        }

        /* 最近考试记录 */
        .recent-exams {
            background: white;
            border-radius: 12px;
            box-shadow: var(--card-shadow);
            margin-bottom: 2rem;
        }

        .exam-item {
            padding: 1rem 1.5rem;
            border-bottom: 1px solid rgba(0, 0, 0, 0.05);
            transition: var(--transition);
        }

        .exam-item:hover {
            background-color: rgba(67, 97, 238, 0.05);
        }

        .exam-item:last-child {
            border-bottom: none;
        }

        .exam-name {
            font-weight: 600;
            margin-bottom: 0.25rem;
        }

        .exam-course {
            color: #6c757d;
            font-size: 0.875rem;
            margin-bottom: 0.25rem;
        }

        .exam-student {
            color: var(--primary);
            font-weight: 500;
            font-size: 0.875rem;
        }

        .exam-score {
            text-align: right;
        }

        .exam-score .score {
            font-size: 1.25rem;
            font-weight: 700;
            color: var(--success);
        }

        .exam-score .percentage {
            font-size: 0.875rem;
            color: #6c757d;
        }

        /* 加载动画 */
        .loading {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 200px;
        }

        .spinner-border {
            color: var(--primary);
        }

        /* 错误提示 */
        .error-message {
            background: #f8d7da;
            color: #721c24;
            padding: 1rem;
            border-radius: 8px;
            margin-bottom: 1rem;
            border: 1px solid #f5c6cb;
        }

        .footer {
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            color: white;
            padding: 2rem 0;
            margin-top: auto;
        }
        .teacher .footer {
            background: linear-gradient(135deg, var(--teacher-accent), #3a0ca3);
        }
        .copyright {
            text-align: center;
            padding-top: 1.5rem;
            margin-top: 1.5rem;
            border-top: 1px solid rgba(255, 255, 255, 0.1);
            color: rgba(255, 255, 255, 0.7);
            font-size: 0.9rem;
        }
    </style>
</head>
<body>
    <!-- 导航栏（与主页一致） -->
    <nav class="navbar navbar-expand-lg navbar-dark">
        <div class="container">
            <a class="navbar-brand" href="#">
                <i class="fas fa-chalkboard-teacher"></i>在线考试系统
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav me-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="/home/manage"><i class="fas fa-home"></i> 主页</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/exam/manage"><i class="fas fa-tasks"></i> 考试管理</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/teacher/question/manage"><i class="fas fa-book"></i> 题库管理</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="/teacher/score/analysis"><i class="fas fa-chart-bar"></i> 成绩分析</a>
                    </li>
                </ul>
                <ul class="navbar-nav ms-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="/teacher/profile">
                            <i class="fas fa-user-circle"></i> 个人信息
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/logout">
                            <i class="fas fa-sign-out-alt"></i> 退出登录
                        </a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <!-- 主内容 -->
    <div class="container main-content">
        <!-- 页面标题 -->
        <div class="page-header">
            <h1 class="page-title">
                <i class="fas fa-chart-line"></i> 成绩统计分析
            </h1>
            <p class="page-subtitle">查看所有学生的成绩统计、趋势分析和排名情况</p>
            
            <!-- 课程切换选择器 -->
            <div class="row mt-3">
                <div class="col-md-6">
                    <div class="d-flex align-items-center">
                        <label for="courseSelect" class="form-label me-3 mb-0 fw-bold">课程筛选：</label>
                        <select id="courseSelect" class="form-select" style="max-width: 300px;">
                            <option value="">全部课程</option>
                        </select>
                        <button id="refreshBtn" class="btn btn-outline-primary ms-2" type="button">
                            <i class="fas fa-sync-alt"></i> 刷新
                        </button>
                    </div>
                </div>
                <div class="col-md-6 text-end">
                    <div class="current-course-info">
                        <span id="currentCourseName" class="badge bg-primary fs-6">全部课程</span>
                    </div>
                </div>
            </div>
        </div>

        <!-- 错误提示 -->
        <div id="errorMessage" class="error-message" style="display: none;"></div>

        <!-- 统计卡片 -->
        <div class="row mb-4">
            <div class="col-md-3 mb-3">
                <div class="stats-card">
                    <div class="stats-icon" style="background: linear-gradient(135deg, var(--primary), var(--secondary));">
                        <i class="fas fa-users"></i>
                    </div>
                    <div class="stats-number" id="totalStudents">0</div>
                    <div class="stats-label">总学生数</div>
                </div>
            </div>
            <div class="col-md-3 mb-3">
                <div class="stats-card">
                    <div class="stats-icon" style="background: linear-gradient(135deg, var(--success), #45a049);">
                        <i class="fas fa-file-alt"></i>
                    </div>
                    <div class="stats-number" id="totalExams">0</div>
                    <div class="stats-label">总考试数</div>
                </div>
            </div>
            <div class="col-md-3 mb-3">
                <div class="stats-card">
                    <div class="stats-icon" style="background: linear-gradient(135deg, var(--info), #1976d2);">
                        <i class="fas fa-chart-bar"></i>
                    </div>
                    <div class="stats-number" id="averageScore">0</div>
                    <div class="stats-label">平均分</div>
                </div>
            </div>
            <div class="col-md-3 mb-3">
                <div class="stats-card">
                    <div class="stats-icon" style="background: linear-gradient(135deg, var(--warning), #f57c00);">
                        <i class="fas fa-percentage"></i>
                    </div>
                    <div class="stats-number" id="passRate">0%</div>
                    <div class="stats-label">及格率</div>
                </div>
            </div>
        </div>

        <!-- 图表区域 -->
        <div class="row">
            <!-- 成绩趋势图 -->
            <div class="col-lg-8 mb-4">
                <div class="chart-card">
                    <div class="chart-header">
                        <div>
                            <i class="fas fa-chart-line"></i>
                            成绩趋势分析
                        </div>
                    </div>
                    <div class="chart-body">
                        <div id="trendChart" class="chart-container"></div>
                    </div>
                </div>
            </div>

            <!-- 成绩分布图 -->
            <div class="col-lg-4 mb-4">
                <div class="chart-card">
                    <div class="chart-header">
                        <div>
                            <i class="fas fa-chart-pie"></i>
                            成绩分布
                        </div>
                    </div>
                    <div class="chart-body">
                        <div id="distributionChart" class="chart-container"></div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 学生排名和最近考试记录 -->
        <div class="row">
            <!-- 学生排名 -->
            <div class="col-lg-6 mb-4">
                <div class="ranking-card">
                    <div class="ranking-header">
                        <i class="fas fa-trophy"></i>
                        学生成绩排名
                        <a href="/teacher/score/ranking" class="btn btn-sm btn-outline-primary ms-auto">
                            查看全部
                        </a>
                    </div>
                    <div id="rankingList">
                        <div class="loading">
                            <div class="spinner-border" role="status">
                                <span class="visually-hidden">加载中...</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 最近考试记录 -->
            <div class="col-lg-6 mb-4">
                <div class="recent-exams">
                    <div class="ranking-header">
                        <i class="fas fa-clock"></i>
                        最近考试记录
                    </div>
                    <div id="recentExamsList">
                        <div class="loading">
                            <div class="spinner-border" role="status">
                                <span class="visually-hidden">加载中...</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 页脚（与主页一致） -->
    <footer class="footer">
        <div class="container text-center py-4">
            <a href="https://gitee.com/sorrymaker04/onlineexam-workload" target="_blank"><i class="fab fa-github fa-2x"></i></a>
            <div class="copyright mt-2">
                &copy; 2025 版权所有 北城在线考试系统小组 12 Team
            </div>
        </div>
    </footer>

    <script src="/js/bootstrap.bundle.min.js"></script>
    <script>
        // 全局变量
        let trendChart, distributionChart;
        let currentCourseId = ''; // 当前选中的课程ID
        let teacherCourses = []; // 教师课程列表

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            initializeCharts();
            loadTeacherCourses();
            loadAllData();
            
            // 绑定事件
            document.getElementById('courseSelect').addEventListener('change', onCourseChange);
            document.getElementById('refreshBtn').addEventListener('click', loadAllData);
        });

        // 初始化图表
        function initializeCharts() {
            trendChart = echarts.init(document.getElementById('trendChart'));
            distributionChart = echarts.init(document.getElementById('distributionChart'));
            
            // 响应式调整
            window.addEventListener('resize', function() {
                trendChart.resize();
                distributionChart.resize();
            });
        }

        // 加载教师课程列表
        function loadTeacherCourses() {
            fetch('/teacher/score/api/teacher-courses')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        teacherCourses = data.data;
                        updateCourseSelect();
                    } else {
                        showError('获取课程列表失败：' + data.message);
                    }
                })
                .catch(error => {
                    console.error('获取课程列表失败:', error);
                    showError('获取课程列表失败');
                });
        }

        // 更新课程选择器
        function updateCourseSelect() {
            const select = document.getElementById('courseSelect');
            const currentValue = select.value;
            
            // 清空现有选项（保留"全部课程"选项）
            select.innerHTML = '<option value="">全部课程</option>';
            
            // 添加课程选项
            teacherCourses.forEach(course => {
                const option = document.createElement('option');
                option.value = course.courseId;
                option.textContent = `${course.courseCode} - ${course.courseName}`;
                select.appendChild(option);
            });
            
            // 恢复之前的选择
            if (currentValue) {
                select.value = currentValue;
            }
        }

        // 课程切换事件
        function onCourseChange() {
            const select = document.getElementById('courseSelect');
            currentCourseId = select.value;
            
            // 更新当前课程名称显示
            const currentCourseName = document.getElementById('currentCourseName');
            if (currentCourseId) {
                const selectedCourse = teacherCourses.find(c => c.courseId == currentCourseId);
                currentCourseName.textContent = selectedCourse ? `${selectedCourse.courseCode} - ${selectedCourse.courseName}` : '未知课程';
            } else {
                currentCourseName.textContent = '全部课程';
            }
            
            // 重新加载数据
            loadAllData();
        }

        // 加载所有数据
        function loadAllData() {
            loadStatistics();
            loadTrendData();
            loadDistributionData();
            loadStudentRanking();
            loadRecentExams();
        }

        // 加载统计数据
        function loadStatistics() {
            const url = currentCourseId ? `/teacher/score/api/statistics/${currentCourseId}` : '/teacher/score/api/statistics';
            
            fetch(url)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        updateStatistics(data.data);
                    } else {
                        showError('获取统计数据失败：' + data.message);
                    }
                })
                .catch(error => {
                    console.error('获取统计数据失败:', error);
                    showError('获取统计数据失败');
                });
        }

        // 更新统计数据
        function updateStatistics(statistics) {
            document.getElementById('totalStudents').textContent = statistics.totalStudents || 0;
            document.getElementById('totalExams').textContent = statistics.totalExams || 0;
            document.getElementById('averageScore').textContent = (statistics.averageScore || 0).toFixed(1);
            document.getElementById('passRate').textContent = (statistics.passRate || 0).toFixed(1) + '%';
        }

        // 加载趋势数据
        function loadTrendData() {
            const url = currentCourseId ? `/teacher/score/api/trend/${currentCourseId}` : '/teacher/score/api/trend';
            
            fetch(url)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        updateTrendChart(data.data);
                    } else {
                        showError('获取趋势数据失败：' + data.message);
                    }
                })
                .catch(error => {
                    console.error('获取趋势数据失败:', error);
                    showError('获取趋势数据失败');
                });
        }

        // 更新趋势图
        function updateTrendChart(trendData) {
            const option = {
                title: {
                    text: '成绩趋势分析',
                    left: 'center',
                    textStyle: {
                        fontSize: 16,
                        fontWeight: 'bold'
                    }
                },
                tooltip: {
                    trigger: 'axis',
                    formatter: function(params) {
                        const data = params[0];
                        return `${data.name}<br/>平均分: ${data.value}`;
                    }
                },
                xAxis: {
                    type: 'category',
                    data: trendData.examDates || [],
                    axisLabel: {
                        rotate: 45
                    }
                },
                yAxis: {
                    type: 'value',
                    name: '平均分',
                    min: 0,
                    max: 100
                },
                series: [{
                    name: '平均分',
                    type: 'line',
                    data: trendData.averageScores || [],
                    smooth: true,
                    lineStyle: {
                        color: '#4361ee',
                        width: 3
                    },
                    itemStyle: {
                        color: '#4361ee'
                    },
                    areaStyle: {
                        color: {
                            type: 'linear',
                            x: 0,
                            y: 0,
                            x2: 0,
                            y2: 1,
                            colorStops: [{
                                offset: 0, color: 'rgba(67, 97, 238, 0.3)'
                            }, {
                                offset: 1, color: 'rgba(67, 97, 238, 0.1)'
                            }]
                        }
                    }
                }]
            };
            
            trendChart.setOption(option);
        }

        // 加载分布数据
        function loadDistributionData() {
            const url = currentCourseId ? `/teacher/score/api/distribution/${currentCourseId}` : '/teacher/score/api/distribution';
            
            fetch(url)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        updateDistributionChart(data.data);
                    } else {
                        showError('获取分布数据失败：' + data.message);
                    }
                })
                .catch(error => {
                    console.error('获取分布数据失败:', error);
                    showError('获取分布数据失败');
                });
        }

        // 更新分布图
        function updateDistributionChart(distributionData) {
            const option = {
                title: {
                    text: '成绩分布',
                    left: 'center',
                    textStyle: {
                        fontSize: 16,
                        fontWeight: 'bold'
                    }
                },
                tooltip: {
                    trigger: 'item',
                    formatter: '{a} <br/>{b}: {c} ({d}%)'
                },
                legend: {
                    orient: 'vertical',
                    left: 'left',
                    data: distributionData.ranges || []
                },
                series: [{
                    name: '成绩分布',
                    type: 'pie',
                    radius: '50%',
                    data: (distributionData.ranges || []).map((range, index) => ({
                        value: distributionData.counts[index] || 0,
                        name: range
                    })),
                    emphasis: {
                        itemStyle: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    }
                }]
            };
            
            distributionChart.setOption(option);
        }

        // 加载学生排名
        function loadStudentRanking() {
            const url = currentCourseId ? `/teacher/score/api/student-ranking/${currentCourseId}` : '/teacher/score/api/student-ranking';
            
            fetch(url)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        updateStudentRanking(data.data);
                    } else {
                        showError('获取学生排名失败：' + data.message);
                    }
                })
                .catch(error => {
                    console.error('获取学生排名失败:', error);
                    showError('获取学生排名失败');
                });
        }

        // 更新学生排名
        function updateStudentRanking(rankingData) {
            const container = document.getElementById('rankingList');
            
            if (!rankingData || rankingData.length === 0) {
                container.innerHTML = '<div class="p-3 text-center text-muted">暂无排名数据</div>';
                return;
            }

            const html = rankingData.slice(0, 5).map((student, index) => {
                const rankClass = index < 3 ? 'top3' : '';
                return `
                    <div class="ranking-item">
                        <div class="ranking-info">
                            <div class="ranking-number ${rankClass}">${student.rank}</div>
                            <div class="student-info">
                                <h6>${student.studentName}</h6>
                                <small>${student.studentId}</small>
                            </div>
                        </div>
                        <div class="ranking-score">
                            <div class="score">${student.averageScore.toFixed(1)}</div>
                            <div class="exam-count">${student.examCount}次考试</div>
                        </div>
                    </div>
                `;
            }).join('');

            container.innerHTML = html;
        }

        // 加载最近考试记录
        function loadRecentExams() {
            const url = currentCourseId ? `/teacher/score/api/recent-records/${currentCourseId}?limit=5` : '/teacher/score/api/recent-records?limit=5';
            
            fetch(url)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        updateRecentExams(data.data);
                    } else {
                        showError('获取最近考试记录失败：' + data.message);
                    }
                })
                .catch(error => {
                    console.error('获取最近考试记录失败:', error);
                    showError('获取最近考试记录失败');
                });
        }

        // 更新最近考试记录
        function updateRecentExams(examsData) {
            const container = document.getElementById('recentExamsList');
            
            if (!examsData || examsData.length === 0) {
                container.innerHTML = '<div class="p-3 text-center text-muted">暂无考试记录</div>';
                return;
            }

            const html = examsData.map(exam => {
                const percentage = ((exam.score / exam.totalScore) * 100).toFixed(1);
                const examDate = new Date(exam.examTime).toLocaleDateString();
                
                return `
                    <div class="exam-item">
                        <div class="d-flex justify-content-between align-items-start">
                            <div class="flex-grow-1">
                                <div class="exam-name">${exam.examName}</div>
                                <div class="exam-course">${exam.courseName}</div>
                                <div class="exam-student">${exam.studentName} (${exam.studentId})</div>
                                <small class="text-muted">${examDate}</small>
                            </div>
                            <div class="exam-score">
                                <div class="score">${exam.score}/${exam.totalScore}</div>
                                <div class="percentage">${percentage}%</div>
                            </div>
                        </div>
                    </div>
                `;
            }).join('');

            container.innerHTML = html;
        }

        // 显示错误信息
        function showError(message) {
            const errorDiv = document.getElementById('errorMessage');
            errorDiv.textContent = message;
            errorDiv.style.display = 'block';
            
            setTimeout(() => {
                errorDiv.style.display = 'none';
            }, 5000);
        }
    </script>
</body>
</html> 